package com.keai.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.keai.constant.MessageConst;
import com.keai.constant.RedisConst;
import com.keai.entity.PageResult;
import com.keai.entity.QueryPageBean;
import com.keai.entity.Result;
import com.keai.pojo.Setmeal;
import com.keai.service.SetmealService;
import com.keai.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Reference
    SetmealService setmealService;

    @Autowired
    JedisPool jedisPool;

        @RequestMapping("/upload")
        public Result upload(MultipartFile imgFile){

        try {
            //生成一个唯一的文件
            //1. uuid
            String uuid = UUID.randomUUID().toString().replace("-", "");
            //2. 截取后缀名
            //原始文件名
            String originalFilename = imgFile.getOriginalFilename();
            //截取后缀名
            String extendName = originalFilename.substring(originalFilename.lastIndexOf("."));
            //拼接
            String uploadFileName = uuid + extendName;
            QiniuUtils.upload2Qiniu(imgFile.getBytes(),uploadFileName);
            //执行到此说明文件已经上传完成，把图片名称存储到redis中
            /**
             * 参数1： set集合的名称
             * 参数2： 图片名称
             */
            jedisPool.getResource().sadd(RedisConst.SETMEAL_PIC_RESOURCES,uploadFileName);
            return new Result(true,MessageConst.PIC_UPLOAD_SUCCESS ,uploadFileName);
        } catch (IOException e) {
            e.printStackTrace();
            return  new Result(false, MessageConst.PIC_UPLOAD_FAIL);
        }


    }

    @RequestMapping("/add")
    @PreAuthorize("hasAuthority('SETMEAL_ADD')")
    public Result add(Integer[] checkgroupIds, @RequestBody Setmeal setmeal){
        try {
            setmealService.add(checkgroupIds, setmeal);
            return new Result(true,MessageConst.ADD_SETMEAL_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.ADD_SETMEAL_FAIL);
        }
    }

    @RequestMapping("/findPage")
    @PreAuthorize("hasAuthority('SETMEAL_QUERY')")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        return setmealService.pageQuery(queryPageBean);
    }
}
